package com.zf.yichat.api.controller.lottery;

import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.model.*;
import com.zf.yichat.service.LotteryService;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import com.zf.yichat.vo.IntegralType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 抽奖管理
 */

@RestController
@RequestMapping("lottery")
@Slf4j
public class LotteryController extends BaseController {

    @Autowired
    private LotteryService lotteryService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysDictService sysDictService;

    /**
     * 奖品列表
     * @return
     */
    @PostMapping("prizeList")
    public FsResponse prizeList() {
        List<LotteryPrize> list = lotteryService.queryPrizeList();
        return FsResponseGen.successData(list);
    }

    /**
     * 用户抽奖列表
     * @return
     */
    @PostMapping("lotteryList")
    public FsResponse lotteryList() {
        Long userId = getUserId();

        List<UserLotteryPrize> list = lotteryService.queryLotteryList(userId);
        return FsResponseGen.successData(list);
    }


    /**
     * 抽奖接口
     * @return
     */
    @PostMapping("drawLottery")
    public FsResponse drawLottery() {

        Long userId = getUserId();

        List<LotteryPrize> prizes = lotteryService.queryPrizeList();

        // 获取用户积分
        User user = userService.selectById(userId);
        if (null == user) {
            return FsResponseGen.failMsg("用户不存在, userId:" + userId);
        }

        Integer integral = user.getIntegral();
        //查询配置的玩游戏获取积分
        String score = sysDictService.selectOne(DictKey.sys_dict_lottery_consume_integral).getValue();
        int consumeInteger = Integer.parseInt(score);

        if (integral < consumeInteger) {
            return FsResponseGen.failMsg("对不起，您的积分不足不能进行抽奖！");
        }

        // 计算权重总和
        double totalWeight = 0;
        for (LotteryPrize prize : prizes) {
            totalWeight += prize.getLotteryRate().doubleValue();
        }

        // 生成随机数
        double randomNum = Math.random() * totalWeight;

        // 根据随机数进行抽奖
        double sumWeight = 0;
        for (LotteryPrize prize : prizes) {
            double currentWeight = prize.getLotteryRate().doubleValue();
            sumWeight += currentWeight;

            // 如果随机数小于等于当前权重之和，则中奖
            if (randomNum <= sumWeight) {
                // 新增用户抽奖记录
                lotteryService.addUserLotteryPrize(userId, prize);
                // 更新用户积分
                updateIntegralDetail(IntegralType.LOTTERY_CONSUME, null, -consumeInteger, userId);
                return FsResponseGen.successData(prize);
            }
        }

        return FsResponseGen.successData(null);// 如果都没中奖，返回null或者其他默认奖品
    }

    private void updateIntegralDetail(IntegralType type, String referId, Integer score, Long userId) {

        //增加记录
        UserIntegralDetail detail = new UserIntegralDetail();
        detail.setIntegral(score);
        detail.setReferType(type.getVal());
        detail.setMemo(type.getDesc());
        detail.setUserId(userId);
        detail.setReferId(referId);
        userService.insertUserIntegralDetail(detail);

        //增加积分值
        userService.addIntegral(score, userId);

    }


    /**
     * 获取抽奖规则
     * @return
     */
    @PostMapping("queryLotteryRule")
    public FsResponse queryLotteryRule() {

//        List<LotteryPrizeRule> prizeRules = lotteryPrizeRuleMapper.selectAll();
//        if (prizeRules.size() > 0) {
//            LotteryPrizeRule lotteryPrizeRule = prizeRules.get(0);
//            String content = lotteryPrizeRule.getContent();
//            return FsResponseGen.successData(content);
//        }
        SysDict dict = sysDictService.selectOne(DictKey.sys_dict_lottery_rule);
        return FsResponseGen.successData(dict.getMemo());
    }

}
